#!/usr/bin/env bash
# Usage: goenv version-file [<dir>]
# Summary: Detect the file that sets the current goenv version
set -e
[ -n "$GOENV_DEBUG" ] && set -x

target_dir="$1"

find_local_version_file() {
  local root="$1"
  while ! [[ "$root" =~ ^//[^/]*$ ]]; do
    if [ -e "${root}/.go-version" ]; then
      echo "${root}/.go-version"
      return 0
    fi

    if [ -e "${root}/go.mod" ] && [ "$GOENV_GOMOD_VERSION_ENABLE" == "1" ]; then
      echo "${root}/go.mod"
      return 0
    fi

    if [ -z "$root" ]; then
      break
    fi

    root="${root%/*}"
  done
  return 1
}

if [ -n "$target_dir" ]; then
  find_local_version_file "$target_dir"
else
  find_local_version_file "$GOENV_DIR" || {
    [ "$GOENV_DIR" != "$PWD" ] && find_local_version_file "$PWD"
  } || echo "${GOENV_ROOT}/version"
fi
